<?php
/**
 * CreateTime: 2022/6/11 21:47
 */

namespace App\Http\Controllers\YsApproval;

use App\Consts\Approval\ApprovalSubmitTypeConsts;
use App\Consts\ClientConsts\ClientConsts;
use App\Consts\ContractConsts\ContractStatusConsts;
use App\Consts\ContractConsts\NewContractApprovalStatus;
use App\Consts\CreditProjectConsts\CreditProjectConsts;
use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Func\ResponseFunc;
use App\Http\Requests\NewContract\RecordContractPost;
use App\Models\Client\ClientModel;
use App\Models\Client\CreditClientModel;
use App\Models\Contract\ContractModel;
use App\Models\modelCreditProjectManage;
use App\Service\Approval\PublicDingTalkApprovalService;
use Illuminate\Http\Exceptions\HttpResponseException;

class YsApprovalController
{
    public function YsApprovalContract(int $contractId){
        $cm = new ContractModel();
    }

    public function test(){
        # 实例化审批类
        $pb = new PublicDingTalkApprovalService();
//        $formComponent = [
//            # 这里的所属单位是单选按钮 [供应链分公司,电商公司,物贸公司]
////            $pb->setTextTextAreaText('审批编号','A'),
//            $pb->setTable('XXX',[
//                    [
//                        $pb->setTableValue("姓名","name"),
//                        $pb->setTableValue("项目","Project")
//                    ],
//                    [
//                        $pb->setTableValue("姓名","name2"),
//                        $pb->setTableValue("项目","Project2")
//                    ]
//                ]
//            )
//        ];
        $a =  '[{\"name\":\"审批编号\",\"value\":\"20220817-6000\"},{\"name\":\"业务负责人\",\"value\":\"liupeng\"},{\"name\":\"业务经办人\",\"value\":\"liupeng\"},{\"name\":\"客户名称\",\"value\":\"自贡银行股份有限公司\"},{\"name\":\"客户类别\",\"value\":1},{\"name\":\"预付/赊销\",\"value\":2},{\"name\":\"项目名称\",\"value\":\"测试项目\"},{\"name\":\"业务模式\",\"value\":\"{\\\"modelType\\\":1,\\\"modelValue\\\":1}\"},{\"name\":\"业务板块\",\"value\":\"{\\\"radioList\\\":[{\\\"title\\\":\\\"钢铁\\\",\\\"childList\\\":[]},{\\\"title\\\":\\\"铁建\\\",\\\"childList\\\":[\\\"钢铁\\\",\\\"水泥\\\"]},{\\\"title\\\":\\\"矿产\\\",\\\"childList\\\":[]},{\\\"title\\\":\\\"能源\\\",\\\"childList\\\":[]},{\\\"title\\\":\\\"油品\\\",\\\"childList\\\":[]},{\\\"title\\\":\\\"国际\\\",\\\"childList\\\":[]}],\\\"currentVal\\\":\\\"矿产\\\"}\"},{\"name\":\"信用额度（万）\",\"value\":213123},{\"name\":\"额度使用截止日期\",\"value\":\"2023-08-17 10:07:47\"},{\"name\":\"“三重一大”事项\",\"value\":2},{\"name\":\"初评意见\"},{\"name\":\"确认事项1\",\"value\":[{\"is_ignore_credit_customer\":2,\"credit_client_level\":1,\"credit_client_quota_max\":700000,\"credit_client_approval_quota\":0,\"credit_client_quota_prepaid\":0,\"credit_client_quota_sale\":0,\"credit_project_client_id\":37,\"department_quota_max_count\":0,\"department_quota_remainder_count\":0,\"credit_project_business_department_id\":1,\"credit_project_current_project_list\":[]}]},{\"name\":\"信用分布\",\"value\":[]},{\"name\":\"截止\",\"value\":\"{\\n    \\\"finance_end_time\\\": \\\"2022-08-04T07:38:08.995Z\\\",\\n    \\\"accounts_receivable_balance\\\": 213123,\\n    \\\"prepaid_account_balance\\\": 21321312\\n}\"},{\"name\":\"该客户应收账款余额（万元）\",\"value\":\"{\\n    \\\"finance_end_time\\\": \\\"2022-08-04T07:38:08.995Z\\\",\\n    \\\"accounts_receivable_balance\\\": 213123,\\n    \\\"prepaid_account_balance\\\": 21321312\\n}\"},{\"name\":\"该客户预付账款余额（万元）\",\"value\":\"{\\n    \\\"finance_end_time\\\": \\\"2022-08-04T07:38:08.995Z\\\",\\n    \\\"accounts_receivable_balance\\\": 213123,\\n    \\\"prepaid_account_balance\\\": 21321312\\n}\"},{\"name\":\"额度分布\",\"value\":\"{\\n    \\\"finance_end_time\\\": \\\"2022-08-04T07:38:08.995Z\\\",\\n    \\\"accounts_receivable_balance\\\": 213123,\\n    \\\"prepaid_account_balance\\\": 21321312\\n}\"},{\"name\":\"信用类别\",\"value\":\"年度\"},{\"name\":\"审议方式\",\"value\":\"会签\"}]';
        $formComponent = json_decode(stripslashes($a),true);
        dd($formComponent);
        $res = $pb->sendApproval(
            999,
            0,
            $formComponent,
            [
                'sqlComponent' => [],
                'file_ids' => "",
                'remark' => ""
            ]
        );
        return ResponseFunc::returnJson(
            'ok',
            [
                "ding_talk_approval_id" => $res
            ],
            '发起审批实例成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS,
        );
    }

    /**
     * 根据客户信用评价表审批 发起对客户->信用客户的审批
     * @param $clientId
     * @return \Illuminate\Http\JsonResponse
     */
    public function ApprovalJoinCreditClient($clientId){
        $data = request()->all();
        $supplier_select = isset($data['form']['customer_supplier_select']) ? $data['form']['customer_supplier_select'] : false;
        if(!$supplier_select){
            throw new HttpResponseException(ResponseFunc::returnJson(
                'error',
                null,
                "所属单位不能为空",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }
        $other_files = isset($data['form']['files']) ? implode(",",array_column($data['form']['files'],"file_id")) : "";
        $remark = $data['form']['remark'] ?? "";
        $clientModel = new ClientModel();
        $creditClientModel = new CreditClientModel();
        $creditClientInfo = $creditClientModel->getCreditClientInfoByClientId($clientId,[
            'client_id',# 客户id
            'credit_client_id',#信用客户表id
            'credit_client_type', #客户类别性质
            'credit_client_evaluation_rating',#总得分
            'credit_client_quota_max',# 额度上限 单位元
            'credit_client_level', # 信用评价等级
            'credit_client_evaluation_info_file_ids' # 信用评价相关附件
        ]);
        # 相关文件
        # 同时加上新上传的附件
        $files = $creditClientInfo['credit_client_evaluation_info_file_ids'];
        if($other_files){
            $files .= ",".$other_files;
        }

        # 总得分
        $totalPoint = $creditClientInfo['credit_client_evaluation_rating'];
        # 额度上限单位万元
        $creditClientQuotaMax = ($creditClientInfo['credit_client_quota_max']/10000);
        # 客户类别
        $creditClientType = app()->gcHelper->getDictionaryMapAuditValueByParentKey(
            ClientConsts::CLIENT_TYPE,
            $creditClientInfo['credit_client_type']);
        $creditClientLevel = app()->gcHelper->getDictionaryMapAuditValueByParentKey(
            ClientConsts::CREDIT_CLIENT_LEVEL,
            $creditClientInfo['credit_client_level']);

        $clientInfo = $clientModel->getClientInfoByClientId($creditClientInfo['client_id'],[
            'client_name',
            'client_economic_type', # 企业性质 1国有 2非国有
        ]);
        # 实例化审批类
        $pb = new PublicDingTalkApprovalService();
        # 构建审批表单
        $clientName = $clientInfo['client_name'];
        $clientEconomicTypeName = app()->gcHelper->getDictionaryMapAuditValueByParentKey(
            ClientConsts::ECONOMIC_TYPE,
            $clientInfo['client_economic_type']);
        $formComponent = [
            # 这里的所属单位是单选按钮 [供应链分公司,电商公司,物贸公司]
            $pb->setTextTextAreaText('所属单位',$supplier_select),
            $pb->setTextTextAreaText('被评价客户全称',$clientName),
            # 这里的客户企业性质是单选按钮 [国有（含国有控股）,非国有]
            $pb->setTextTextAreaText('客户企业性质',$clientEconomicTypeName),
            # 这里的客户类别性质是单选按钮 [A类,B类,C类,D类]
            $pb->setTextTextAreaText('客户类别',$creditClientType),
            # 这里的信用级别是单选按钮 [一级,二级,三级]
            $pb->setTextTextAreaText('信用级别',$creditClientLevel),
            $pb->setTextTextAreaText('信用额度上限（万元）',$creditClientQuotaMax),
            # 这里的备注是多行文本
            $pb->setTextTextAreaText('备注',$remark),
            # 这里的总得分是数字框
            $pb->setMoneyNumberFuc('总得分',(int)$totalPoint),
        ];
        $sqlComponent= $formComponent;

        $formComponent[] = $pb->setFiles('附件',$files);
        $sqlComponent[] = [
            "name" => "附件",
            "value" => $files
        ];

        $res = $pb->sendApproval(
            ApprovalSubmitTypeConsts::SUBMIT_CREDIT_CLIENT,
            $clientId,
            $formComponent,
            [
                'sqlComponent' => $sqlComponent,
                'file_ids' => $files,
                'remark' => $remark
            ]
        );
        return ResponseFunc::returnJson(
            'ok',
            [
                "ding_talk_approval_id" => $res
            ],
            '发起审批实例成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS,
        );
    }

    public function YsApprovalClientSend($clientId){
        # 信用客户审批开始
        $creditClientModel = new CreditClientModel();
        $clientModel = new ClientModel();

        $creditClientId = $creditClientModel->getCreditClientInfoByClientId($clientId,[
                'credit_client_id'
        ])['credit_client_id'];
        # 修改客户表是否信用客户 is_credit_client 客户类型 client_type
        $clientModel->editClient([
            'client_id' => $clientId,
            'is_credit_client' => 1,
            'client_type' => 2
        ]);
        # 修改信用客户送审表状态为审批通过
        $creditClientModel->editCreditClient($creditClientId,[
            'audit_status' => 3
        ]);

        return ResponseFunc::returnJson(
            'ok',
            [
                "ding_talk_approval_id" => 1
            ],
            '送审信用客户成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS,
        );
    }


    /**
     * 送审黑名单
     * @param $creditClientId
     * @return \Illuminate\Http\JsonResponse
     */
    public function ApprovalJoinBlackList($creditClientId): \Illuminate\Http\JsonResponse
    {
        $clientModel = new ClientModel();
        $dictionaryValue = app()->gcHelper->getDictionaryInfoByDictionaryKey(ClientConsts::CLIENT_STATUS_TYPE_BLACKLIST,[
            'dictionary_value'
        ])['dictionary_value'];

        // 修改客户状态
        $res = $clientModel->editClient([
            'client_id' => $creditClientId,
            'client_type' => $dictionaryValue
        ]);
        return ResponseFunc::returnJson(
            'ok',
            [
                "credit_client_id" => $res
            ],
            '加入黑名单成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS,
        );
    }

    public function ApprovalDelBlackList($creditClientId): \Illuminate\Http\JsonResponse
    {
        $clientModel = new ClientModel();
        $dictionaryValue = app()->gcHelper->getDictionaryInfoByDictionaryKey(ClientConsts::CLIENT_STATUS_TYPE_NORMAL,[
            'dictionary_value'
        ])['dictionary_value'];

        // 修改客户状态
        $res = $clientModel->editClient([
            'client_id' => $creditClientId,
            'client_type' => $dictionaryValue
        ]);
        return ResponseFunc::returnJson(
            'ok',
            [
                "credit_client_id" => $res
            ],
            '移除黑名单成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS,
        );
    }



    // 合同作废
    public function ApprovalContractAbandon($contractId){
        $contractModel = new ContractModel();
        $dictionaryValue = app()->gcHelper->getDictionaryInfoByDictionaryKey(ContractStatusConsts::CONTRACT_STATUS_ABANDON,[
            'dictionary_value'
        ])['dictionary_value'];

        // 修改客户状态
        $res = $contractModel->editContract([
            'contract_id' => $contractId,
            'contract_status' => $dictionaryValue
        ]);
        return ResponseFunc::returnJson(
            'ok',
            [
                "contract_id" => $res
            ],
            '作废合同成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS,
        );
    }

    // 合同待送签
    public function ApprovalContractSign($contractId){
        $contractModel = new ContractModel();
        $dictionaryValue = app()->gcHelper->getDictionaryInfoByDictionaryKey(ContractStatusConsts::CONTRACT_STATUS_STAY_SIGN,[
            'dictionary_value'
        ])['dictionary_value'];

        // 修改客户状态
        $res = $contractModel->editContract([
            'contract_id' => $contractId,
            'contract_status' => $dictionaryValue
        ]);
        return ResponseFunc::returnJson(
            'ok',
            [
                "contract_id" => $res
            ],
            '合同送审成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS,
        );
    }

    // 合同归档
    public function ApprovalContractRecord($contractId,RecordContractPost $recordContractPost){
        $data = $recordContractPost->all();
        $contractModel = new ContractModel();
        $dictionaryValue = app()->gcHelper->getDictionaryInfoByDictionaryKey(ContractStatusConsts::CONTRACT_STATUS_RECORD,[
            'dictionary_value'
        ])['dictionary_value'];
        if(isset($data['record_contract_file'])){
            $data['record_contract_file'] = implode(",",array_column($data['record_contract_file'],"file_id"));
        }else{
            return ResponseFunc::returnJson(
                'error',
                null,
                '合同原件不能为空',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            );
        }
        // 校验合同归档状态 如果合同状态不为履约中则不允许归档
        $contractInfo = $contractModel->getContractInfo($contractId,['contract_status','contract_sign_time']);
        if(!$contractInfo){
            return ResponseFunc::returnJson(
                'error',
                null,
                '当前合同不存在',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            );
        }

        if($contractInfo['contract_status']!= NewContractApprovalStatus::CONTRACT_APPROVAL_LYWC && $contractInfo['contract_status']!= NewContractApprovalStatus::CONTRACT_APPROVAL_YQS){
            return ResponseFunc::returnJson(
                'error',
                null,
                '合同未履约或已归档',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            );
        }

        // 判断合同是否填写了签订信息
//        if(!$contractInfo['contract_sign_time']){
//            return ResponseFunc::returnJson(
//                'error',
//                null,
//                '请先完善合同签署信息',
//                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
//            );
//        }



        // 修改客户状态
        $res = $contractModel->editContract([
            'contract_id' => $contractId,
            'contract_status' => $dictionaryValue,
            'record_owner_id' => $data['record_owner_id'],
            'record_department_id' => $data['record_department_id'],
            'record_location' => $data['record_location'] ?? ""
        ]);

        return ResponseFunc::returnJson(
            'ok',
            [
                "contract_id" => $res
            ],
            '合同归档成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS,
        );
    }

    public function ApprovalCreditProject($creditProjectId){
        $creditProjectModel = new modelCreditProjectManage();

        $dictionaryValue = app()->gcHelper->getDictionaryInfoByDictionaryKey(CreditProjectConsts::CREDIT_PROJECT_STATUS_1,[
              'dictionary_value'
        ])['dictionary_value'];

        // 修改客户状态
        $res = $creditProjectModel->editSimpleCreditProjectByCreditProjectId(
            [
                'id' => $creditProjectId,
                'credit_project_status' => $dictionaryValue
            ]
        );
        return ResponseFunc::returnJson(
            'ok',
            [
                "contract_id" => $res
            ],
            '信用项目送审成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS,
        );


    }

}